package com.javaweb.service.impl;

import com.javaweb.common.BusinessConstants;
import com.javaweb.dao.ArticleDao;
import com.javaweb.dao.UserDao;
import com.javaweb.model.Article;
import com.javaweb.service.ArticleService;
import com.javaweb.service.dto.ArticleConditionDto;
import com.javaweb.service.dto.ArticleDto;
import com.javaweb.service.dto.PageResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import java.util.ArrayList;
import java.util.List;

import static com.javaweb.common.BusinessConstants.OPER_FAILED;

/**
 * @desc:
 * @author: Ping
 * @date: 2024/10/16 9:47
 */

@Service
@Slf4j
public class ArticleServiceImpl implements ArticleService {

    @Autowired
    private UserDao userDao ;
    @Autowired
    private ArticleDao articleDao ;


    @Transactional
    @Override
    public int publishArticle(String userId, String articleId) {

        Integer ret =  articleDao.updateStatus(Integer.valueOf(articleId),
                               BusinessConstants.ARTICLE_PUBLISHED) ;
        if (ret > 0) {
            ret = userDao.updateScore(Integer.valueOf(userId),
                    BusinessConstants.ARTICLE_SCORE) ;
        } else {
            log.error("publish article : update status failed." ) ;
            return OPER_FAILED;
        }
        log.info("publish article successfully." ) ;
        return ret;
    }

    @Override
    public PageResult<ArticleDto> queryByArticleCondition(ArticleConditionDto articleConditionDto, Integer pageNum, Integer pageSize) {
       /*
        *  先查总数
        */
        int total = articleDao.selectCount(articleConditionDto) ;
        if (total == 0) {
            return PageResult.empty() ;
        }
        // 再查分页数据
        List<Article> articles = articleDao.selectByPage(articleConditionDto, pageNum, pageSize) ;
        List<ArticleDto> articleDtos = new ArrayList<>() ;
        // 设置 authorName
        if (! ObjectUtils.isEmpty(articles)) {
            articles.forEach(article -> {
                ArticleDto articleDto = ArticleDto.fromEntity(article);
                articleDto.setAuthorName(userDao.selectOneById(article.getUserId()).getName());
                articleDtos.add(articleDto);
            }) ;

        }
        return new PageResult<ArticleDto>()
                        .setData(articleDtos)
                        .setPageSize(pageSize)
                        .setPageNum(pageNum)
                        .setTotal(total);
    }
}
